<?php

namespace app\model;

class CompanyModel extends BaseModel
{
    protected $name = 'company';

    public const DISABLED = 100; // 禁用
    public const NORMAL = 200;   // 正常


    /**
     * Notes: 企业列表
     * User: chenLei
     * Date: 9/25/25
     * @param $params
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function list($params)
    {
        $where = [];

        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }

        return $this->where($where)->paginate($params['page_size'] ?? 15);
    }

    /**
     * Notes: 添加企业
     * User: chenLei
     * Date: 9/25/25
     * @param $params
     * @return bool
     */
    public function add($params)
    {
        if ($this->where('name', $params['name'])->count()) {
            $this->error = '公司名称已存在';
            return false;
        }

        $this->save([
            'name' => $params['name'],
            'status' => $params['status'],
        ]);
        return true;
    }


    /**
     * Notes: 修改企业
     * User: chenLei
     * Date: 9/25/25
     * @param $params
     * @return bool
     */
    public function edit($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '公司不存在';
            return false;
        }

        if ($this->where('name', $params['name'])->where('id', '<>', $params['id'])->count()) {
            $this->error = '公司名称已存在';
            return false;
        }

        $info->save([
            'name' => $params['name'],
            'status' => $params['status'],
        ]);
        return true;
    }


    /**
     * Notes: 删除
     * User: chenLei
     * Date: 9/25/25
     * @param $params
     * @return bool
     */
    public function del($params)
    {
        $info = $this->where('id', $params['id'])->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '公司不存在';
            return false;
        }

        $info->delete();
        return true;
    }


    /**
     * Notes: 获取所有企业列表
     * User: chenLei
     * Date: 9/26/25
     * @param $params
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function listAll($params)
    {
        $where = [];
        if (!empty($params['name'])) {
            $where[] = ['name', 'like', '%' . $params['name'] . '%'];
        }
        $where[] = ['status', '=', self::NORMAL];
        return $this->where($where)->field('id,name,create_time')->select();
    }
}